package WxOfficialAccount

import (
	"server/global"

	"github.com/silenceper/wechat/v2"
	"github.com/silenceper/wechat/v2/cache"
	officialAccountConfig "github.com/silenceper/wechat/v2/officialaccount/config"
	"github.com/silenceper/wechat/v2/officialaccount/js"
	"github.com/silenceper/wechat/v2/officialaccount/oauth"
)

//微信SDK For Golang
//https://silenceper.com/wechat/

// AuthLogin Web公众号授权登录
func AuthLogin(jsCode string) (oauth.UserInfo, error) {
	memory := cache.NewMemory()
	cfg := &officialAccountConfig.Config{
		AppID:     global.GL_CONFIG.WxOfficialAccount.AppID,
		AppSecret: global.GL_CONFIG.WxOfficialAccount.AppSecret,
		Token:     "",
		Cache:     memory,
	}
	wc := wechat.NewWechat()
	oa := wc.GetOfficialAccount(cfg)
	u := oa.GetOauth()
	sss, err := u.GetUserAccessToken(jsCode)
	info, err := u.GetUserInfo(sss.AccessToken, sss.OpenID, "")

	if err != nil {
		return oauth.UserInfo{}, err
	}

	return info, err
}

// 获取js-sdk操作实例
func GetJsSdk(uri string) (*js.Config, error) {
	memory := cache.NewMemory()
	cfg := &officialAccountConfig.Config{
		AppID:     global.GL_CONFIG.WxOfficialAccount.AppID,
		AppSecret: global.GL_CONFIG.WxOfficialAccount.AppSecret,
		Token:     "",
		Cache:     memory,
	}
	wc := wechat.NewWechat()
	oa := wc.GetOfficialAccount(cfg)
	j := oa.GetJs()

	return j.GetConfig(uri)
}
